package com.qk.management.web.filter;
import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.jwt.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import java.io.IOException;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-10-11 10:42
 */
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String IGNORE_URLS = "/login";
    private static final String TOKEN = "token";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
        if (ObjectUtil.equals(IGNORE_URLS, path)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(TOKEN);
        if (ObjectUtils.isEmpty(token)) {
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseJwts(token);
            filterChain.doFilter(request, response);
        }catch (Exception e){
            response.setStatus(401);
        }
    }
}
